<?php
namespace control;
/*
*文档目录
*/
class documentCatalogClass extends adIndexClass
{
    private const page  = 'documentCatalog'; # 权限
    private const table = 'document_catalog'; # 数据表
    private const title = '文档目录';
    /**
     * 获取分类名称
     * @param $id
     * @return mixed
     */
    public static function getTypeName($id): mixed
    {
        $type = query(self::table, "id = '$id'");
        if (!empty($type['pid'])) {
            $result = self::getTypeName($type['pid']);
            $name = $result . '->' . $type['name'];
        } else {
            $name = $type['name'] ?? null;
        }
        return $name;
    }
    public static function getCatalogAll($data = [])
    {
        $orderBy = ' ORDER BY list ASC ';
        // 条件
        $data['where'] = $data['where'] ?? "pid='0'";
        // 点击事件
        $data['click'] = $data['click'] ?? "replaceDetail(this, '".self::page."')";
        // 结果
        $result = find(['table'=>self::table, 'where'=> $data['where'] . $orderBy]);
        $style = ($data['where'] == "pid='0'") ? '' : ' class="child-node"';
        $temp = "<ul {$style} {$data['where']}>";
        // 角标
	    $lastone = lastone;
        $textcontent_ico = "<span class='textcontent_ico'></span>";
        if ($result['array']) {
            foreach ($result['array'] as $value) {
                // 角标
                $arrow = "<span class='arrow'  onclick=\"liZoom($(this).parent())\"></span>";
                // 判断下级是否存在
                $data['where'] = " pid='{$value['id']}' ";
                $has = query(self::table, $data['where']. $orderBy);
                if ($has['id']) {
                    $temp .="<li  class='arrow-li' data-id='{$value['id']}' onclick=\"{$data['click']}\">
                                {$arrow}
                                <span class='textcontent'>{$textcontent_ico}{$value['name']}</span>
                            </li>";
                    $temp .= self::getCatalogAll($data);
                } else {
                    $temp .="<li  class='arrow-no-li' data-id='{$value['id']}' onclick=\"{$data['click']}\">
                                {$lastone}
                                <span class='textcontent'>{$textcontent_ico}{$value['name']}</span>
                            </li>";
                }
            }
        }
        $temp .= '</ul>';
        return $temp;
    }


    /**
     * 左侧搜索框
     *
     * @return string
     */
    public function getContainerLeftJson():string
    {
        $json['html'] = self::getCatalogAll([]);
        return json_encode($json, 320);
    }


    /*列表页-查询条件*/
    public function home()
    {
        $all = $this->getCatalogAll([]);
        $rightHtml = <<<EOT
            <div class="container-no">
                <img class="container-no-img" src="{$this->root}img/control/department-no.svg">
                <p class="center gray">暂无分类</p>
            </div>
EOT;
        $html = componentClass::leftNav([
            'title'=>'搜索分类',
            'button'=>"<img class='tool-img' title='新建' onclick=\"layer('" . $this->get('cla') . "','edit',{id:'".suiji()."', pid: 0})\" src='".root."img/control/list_add.svg'>",
            'all'=>$all,
            'rightHtml'=>$rightHtml,
        ]);
        //返回
        return $this->homeFun($html);
    }


    /*编辑分类基本资料-弹出层*/
    public function edit()
    {
        //数据查询
        $info = query(self::table, " id = '".$this->post('id')."' ");
        $pid = $info['pid'] ?:  ($this->post('pid') ?? 0);
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must."分类名称：" => text(["name" => "name","value" => $info['name'], 'class'=> 'text']),
                ],
                [
                    "排序号：" => text(["name" => "list","value" => $info['list'], 'class'=> 'text']).hidden([ 'name'=>'pid', 'value'=>$pid ]),
                ]
            ]
        ]);
        //返回
        return $this->layer(array("title" => "编辑分类基本资料","height" => 200,"html" => $html));
    }
    /*分类基本信息-异步处理*/
    public function editEdit()
    {
        //赋值
        $field = array(
            'pid'  => $this->post('pid') ?? 0,
            "name" => $this->post('name'),       //分类名称
            "list" => $this->post('list'),       //排序号
        );
        $info = query(self::table, " id = '".$this->post('id')."' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑分类的权限";
        } elseif (empty($field['name'])) {
            $json['warn'] = "请填写分类名称";
        } elseif (sqlNum(self::table, "pid = '$field[pid]' and name = '$field[name]' and id != '".$this->post('id')."' ") > 0) {
            $json['warn'] = "该分类已经存在";
        } elseif (!empty($field['list']) && preg_match(checkInteger, $field['list']) == 0) {
            $json['warn'] = "排序号必须为正整数";
        } elseif (empty($this->post('id'))) {
            $json['warn'] = "分类ID号为空";
        } elseif (empty($info['id'])) {
            $field = array_merge($field, ["id" => $this->post('id'), 'stid'=>self::$stid, "time" => $this->time]);
            $json['warn'] = insert(["table" => self::table, "field" => $field]);
        } else {
            $json['warn'] = update(["table" => self::table, "field" => $field, "where" => "id = '".$this->post('id')."'"]);
        }
        if (in_array($json['warn'], array("新增成功","更新成功"))) {
            //添加日志
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text = $this->control['name'].$type."了一个【".self::title."】：分类ID：".$info['id'];
            $this->logText(["type" => self::page, "text" => $text]);
            //提示
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }

    public function detail()
    {
        $info = query(self::table, " id = '".$this->post('id')."' ");
        if (!$this->power(self::page, "see")) {
            $json['warn'] = "你没有查看分类的权限";
        } elseif (empty($this->post('id'))) {
            $json['warn'] = "分类ID为空";
        } elseif (empty($info['id'])) {
            $json['warn'] = "未找到此分类";
        } else {
            $data = [
                "id" => $info['id'],
                "title" => $info['name'],
            ];
            //按钮
            $button = [];
            if ($this->power(self::page, "edit")) {
                $button[] = [
                    "name" => "编辑",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => $info['id'] ],
                    'style' => 'li-btn-blue-bg',
                ];
                $button[] = [
                    "name" => "添加同级",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => suiji(), 'pid'=> $info['pid']],
                ];
                $button[] = [
                    "name" => "添加下级",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => suiji(), 'pid'=> $info['id']],
                ];
                $button[] = [
                    "name"  => "删除",
                    "type"  => "弹出层",
                    "cla"   => $this->get('cla'),
                    "fun"   => "delete",
                    "post"  => ["id" => $info['id']],
                ];
            }
            //生成表单
            $data['html'] = "
                            <div class='tab-button'>".$this->tableShowButton($button)."</div>
                            <div class='tab-content'>
                            ".$this->tableShow([
                                [
                                    [
                                        "分类名称" => $info['name'],
                                        "排序号" => $info['list'],
                                        "创建人" => self::findStaff($info['stid']),
                                        "更新时间" => $info['updateTime'],
                                    ],
                                    [
                                        "创建时间" => $info['time'],
                                    ]
                                ]
                            ])."
                            </div>";
            //生成页面
            $json['warn'] = 2;
            $json['html'] = $data['html'];
        }
        //返回
        return json_encode($json, 320);
    }

    /**
     * 判断是否有文章使用此分类
     * @param $id
     * @return bool
     */
    private function juageDel($id): bool
    {
        $bool = true;
        $type = query(self::table, "pid = '$id'");
        if ($type['id']) {
            $bool = $this->juageDel($type['id']);
        }
        if (static::total(array('table' => 'document', 'where' => "dcid = '$id'")) > 0) {
            return false;
        }
        return $bool;
    }

    public function deleteAll($id)
    {
        $type = query(self::table, "pid = '$id'");
        if ($type['id']) {
            $this->deleteAll($type['id']);
        }
        delete(array('table' => self::table, 'where' => "id = '$id'"));
    }
    /*删除分类*/
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有删除".self::title."的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一条记录都没有选择呢";
        } else {
            $text = '';
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $where = " id = '$id' ";
                $info = query(self::table, $where);
                if (empty($info['id'])) {
                    $text .= "【{$info['name']}】，ID【{$id}】不存在，无法删除";
                } else {
                    if (!$this->juageDel($id)) {
                        $text .= "【{$info['name']}】，ID【{$id}】删除失败，其分类或子分类已在文章中使用";
                        continue;
                    }
                    //递归删除
                    $this->deleteAll($id);
                    //添加记录
                    $text .= "【".$info['name']."】：ID【{$id}】及其子分类删除成功<br>";
                    $x++;
                }
            }
            $text .= "{$this->control['name']}删除了".self::title."如下：".$text;
            // 写入日志
            $this->logText(["type" => self::page, "text" => $text]);
            $_SESSION['warn'] = "删除了{$x}条".self::title;
            $json['warn']     = 2;
            $json['href'] = root."control/adIndex.html?cla=".$this->get('cla')."&fun=home";
        }

        resp:
        return json_encode($json, 320);
    }
}
